/* eslint-disable react/no-string-refs */
import React, { Component } from 'react'
import { inject, observer } from 'mobx-react/index'
import { Dropdown, Menu, message, Modal, Spin, Tooltip } from 'antd'
import { InfoCircleFilled, ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons'
import moment from 'moment'
import Cookies from 'js-cookie'
import CommonTitle from '@/pages/Dashboard/common/Tilte'
import getData from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import { USER_INFO } from '@/Utils/CONST'

import './index.less'

const { confirm } = Modal
const {
  projectEnv,
  orderLink,
  renewLink,
  bdpApi: { operaAuth, instancesCancel },
  quorumManagement: { getQuorumList, deleteQuorum },

} = address

const Quorum_Status = {
  'building': {
    'tooltip': '创建中',
    'icon': require('@/images/fabric/u5993.gif'),
  },
  'running': {
    'tooltip': '运行中',
    'icon': require('@/images/fabric/yunhangzhong.svg'),
  },
  'stoped': {
    'tooltip': '已暂停',
    'icon': require('@/images/fabric/stop.svg'),
  },
  'exiting': {
    'tooltip': '退订中',
    'icon': require('@/images/fabric/u5993.gif'),
  },
  'failed': {
    'tooltip': '创建失败',
    'icon': require('@/images/fabric/error.svg'),
  },
  'ADD': {
    'tooltip': '加入中',
    'icon': require('@/images/fabric/u5993.gif'),
  },
  'CREATING': {
    'tooltip': '创建中',
    'icon': require('@/images/fabric/u5993.gif'),
  },
  'FAIL': {
    'tooltip': '创建失败',
    'icon': require('@/images/fabric/error.svg'),
  },
  'PREPARE_BUILDING': {
    'tooltip': '加入中',
    'icon': require('@/images/fabric/u5993.gif'),
  },
  'PREPARE_SUCCESS': {
    'tooltip': '加入中',
    'icon': require('@/images/fabric/u5993.gif'),
  },
  'EXIT': {
    'tooltip': '退订成功',
    'icon': require('@/images/fabric/error.svg'),
  },
}

@inject('SocketModel', 'RegionId')
@observer
class QuorumCom extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: true,
      networkList: [],
    }
  }
  componentDidMount() {
    this.getNetwokList()
  }

  componentWillReact() {
    const { isCreateQuorum } = this.props.SocketModel
    // 通过socket更新网络状态
    if (isCreateQuorum) {
      this.props.SocketModel.setIsCreateQuorum(false)
      this.getNetwokList()
    }
  }

    // 获取我的网络列表
    getNetwokList = () => {
      getData().get(getQuorumList).then(res => {
        this.setState({
          loading: false,
        })
        if (res && res.status === 200) {
          this.setState({
            networkList: res.data.data,
          })
        }
      }).catch(e => {
        this.setState({
          loading: false,
        })
      })
    }

    // go to 创建网络
    gotoCreateNetwork = () => {
      const curEnv = projectEnv
      if (curEnv === 'sy') {
        const pathname = orderLink.format({ type: 'quorum' })
        window.open(pathname)
      } else {
        this.props.history.push('/dashboard/quorum/createNetwork')
      }
    }

    // 点击网络卡片进入网络详情
    enterDetail = (item) => {
      if (item.status === 'running') {
        Cookies.set('network_name', item.name)
        this.props.history.push({
          pathname: `/dashboard/quorum/network/${item.id}/${item.name}`,
        })
      }
    }

    // 删除当前网络
    deleteNetwork = async(e, item) => {
      e.stopPropagation()
      confirm({
        title: '删除提示',
        className: 'common-confirm-small',
        icon: <InfoCircleFilled />,
        getContainer: () => document.getElementById('quorum-wrapper'),
        content: `确定要删除网络“${item.network_name}”？`,
        onOk() {
          try {
            let res = getData().delete(deleteQuorum.format({ id: item.key }))
            if (res && res.status === 200) {
              message.success('删除网络成功')
              this.getNetwokList()
            }
          } catch (e) {
            message.error('删除网络失败')
          }
        },
        onCancel() {
        },
      })
    }

    // 渲染创建网络状态
    /**
     *
     * @param {string} status
     * 创建中 - building
     * 运行中 - running
     * 已停机 - stoped
     */
    renderStatus = (status) => {
      const title = Quorum_Status[status] && Quorum_Status[status].tooltip || '创建失败'
      const icon = Quorum_Status[status] && Quorum_Status[status].icon || require('@/images/fabric/error.svg')
      return (
        <Tooltip placement="top" title={title}>
          <img src={icon} className="status-icon" alt=""/>
        </Tooltip>
      )
    }

    // 网络名称tooltip
    renderName = (val, len) => {
      if (!val) return ''
      if (val.length > len) {
        return <Tooltip title={val}>
          <span className="name">{val.slice(0, 10)} ...</span>
        </Tooltip>
      } else {
        return <span className="name">{val}</span>
      }
    }

    // 修改cookie值，用于判断退订条件，后续可能改为socket推送
    changeExitingCookies = (id) => {
      let res = JSON.parse(Cookies.get('isExiting'))
      res = res.filter(item => item !== id)
      if (!res.length) {
        Cookies.remove('isExiting')
      } else {
        res = JSON.stringify(res)
        Cookies.set('isExiting', res)
      }
    }

    // 点击退订操作弹窗
    handleExitOpt = async(id, name) => {
      let res = []
      if (Cookies.get('isExiting')) {
        res = JSON.parse(Cookies.get('isExiting'))
      }
      res.push(id)
      res = JSON.stringify(res)
      Cookies.set('isExiting', res)
      const res1 = await getData().get(`${operaAuth}?instanceId=${id}&operType=CANCEL`)
      if (res1 && res1.status === 200) {
        const code = res1.data.data.checkCode || ''
        if (code && code === '0' || code === '00') {
          const res2 = await getData().post(`${instancesCancel}?instanceId=${id}`)
          if (res2 && res2.status === 200) {
            message.success(`实例${name}退订成功`)
            // 重新刷新数据
            this.getNetwokList()
          } else {
            Modal.info({
              title: `退订失败`,
              icon: <ExclamationCircleFilled />,
              className: 'common-info common-info-large',
              getContainer: () => this.refs.quorumWrapper,
              content: '退订失败，实例将继续产生费用。您可以联系客服完成实例退订。客服号码：4001100868',
              onOk() {},
            })
          }
        } else {
          message.warning(res1.data.data.checkMessage || '校验未通过')
        }
      } else {
        message.error('权限校验失败')
      }
      this.changeExitingCookies(id)
    }

    // 页面跳转
    goToLink = (link) => {
      // const location = window.location;
      // const url = location.protocol + '//' + location.hostname; // 协议，域名，端口在apiconfig文件配置
      window.location.href = link
    }

    // 退订/续订点击
    handleMenuClick = async(item, e) => {
      const { id, createTime, name, status, isOwner } = item
      const { key, domEvent } = e
      domEvent.stopPropagation()
      let startTime = new Date(createTime).getTime()
      let curTime = new Date().getTime()
      let diffTime = (curTime - startTime) / (1000 * 60)
      let isCanOpt = false
      let notIncludeId = false
      if (!Cookies.get('isExiting')) {
        notIncludeId = true
      } else {
        let res = JSON.parse(Cookies.get('isExiting'))
        if (!res.includes(id)) {
          notIncludeId = true
        }
      }
      if (status === 'running' && notIncludeId && isOwner) {
        if (key === '0' && diffTime > 30) {
          isCanOpt = true
        } else if (key === '1') {
          isCanOpt = true
        }
      }
      let _this = this
      if (!isCanOpt) {
        let opt = key === '0' ? '退订' : '续订'
        let index = ''
        if (status === 'building') {
          index = 'building'
        } else if (diffTime < 30 && key === '0') {
          index = 'waiting'
        } else if (!isOwner) {
          index = 'noAuth'
        } else if (!notIncludeId) {
          index = 'exiting'
        }
        let obj = {
          'building': `当前实例在创建中，不可${opt}`,
          'waiting': `订购30分钟后可进行退订`,
          'noAuth': `当前用户没有权限，不可${opt}`,
          'exiting': `当前实例在退订中，不可${opt}`,
        }
        Modal.info({
          title: `该实例不可${opt}`,
          icon: <ExclamationCircleFilled />,
          className: 'common-info common-info-small',
          getContainer: () => this.refs.quorumWrapper,
          content: obj[index],
          onOk() {},
        })
      } else if (isCanOpt) {
        // 退订
        if (key === '0') {
          confirm({
            title: '是否退订该实例？',
            className: 'common-confirm-small',
            icon: <ExclamationCircleFilled />,
            getContainer: () => this.refs.quorumWrapper,
            content: `实例${name}退订后不能恢复，退订后账户不再对该实例计费`,
            onOk() {
              _this.handleExitOpt(id, name)
            },
            onCancel() {
            },
          })
        } else if (key === '1') {
          // 续订
          // const regionId = this.props.RegionId.regionId; // 资源池id
          // const instanceId = id; // 实例id
          const res1 = await getData().get(`${operaAuth}?instanceId=${id}&operType=RENEW`)
          if (res1 && res1.status === 200) {
            const code = res1.data.data.checkCode || ''
            if (code && code === '0' || code === '00') {
              this.goToLink(renewLink.format({ instanceId: id, regionId: this.props.RegionId.regionId }))
            } else {
              Modal.info({
                title: `续订失败`,
                icon: <ExclamationCircleFilled />,
                className: 'common-info common-info-large',
                getContainer: () => this.refs.quorumWrapper,
                // content: '续订失败，您可以联系客服完成实例续订。客服号码：4001100868',
                content: `${res1.data.data.checkMessage}`,
                onOk() {},
              })
              // message.warning(res1.data.data.checkMessage || '校验未通过');
            }
          } else {
            message.error('权限校验失败')
          }
          // this.goToLink(renewLink.format({instanceId: id, regionId: this.props.RegionId.regionId}))
        }
      }
    }

    // 渲染续订/退订下拉框
    renderOperation = (item) => {
      const obj = {
        'INTERNET_CUSTOMER': [
          {
            label: '续订',
            key: '1',
          },
        ],
        'GOVERNMENT_CUSTOMER': [
          {
            label: '退订',
            key: '0',
          },
        ],
        'ignore': [
          {
            label: '续订',
            key: '1',
          },
          {
            label: '退订',
            key: '0',
          },
        ],
      }

      const userInfo = JSON.parse(localStorage.getItem(USER_INFO) || '{}')
      const _type = (userInfo && userInfo.userType) || 'ignore'

      if (_type === 'INTERNET_CUSTOMER') {
        // 时间过期
        if (moment(item.dueTime).valueOf() - Date.now() < 0) {
          return null
        }
      }
      const menuData = obj[_type]
      const menu = (
        <Menu onClick={(e) => this.handleMenuClick(item, e)}>
          {
            menuData.map(item => {
              return (
                <Menu.Item key={item.key}>
                  <span>{item.label}</span>
                </Menu.Item>

              )
            })
          }
        </Menu>
      )
      return (
        <Dropdown
          getPopupContainer={() => this.refs.quorumWrapper}
          overlay={menu}
          trigger={['click']}
        >
          <div onClick={e => e.stopPropagation()} className="operate">
            <div className="point"></div>
            <div className="point"></div>
            <div className="point"></div>
          </div>
        </Dropdown>
      )
    }

    render() {
      const { networkList, loading } = this.state
      const { isCreateQuorum } = this.props.SocketModel
      const userInfo = JSON.parse(localStorage.getItem(USER_INFO) || '{}')
      const _type = userInfo && userInfo.userType || 'ignore'
      const timeVisible = _type !== 'GOVERNMENT_CUSTOMER' // 政企用户不显示到期时间
      return (
        <div id="quorum-wrapper" className="quorum-list-page" ref="quorumWrapper">
          {/* mobx: observable 用到才能触发生命周期, 糟糕使用 */}
          <span style={{ display: 'none' }}>{isCreateQuorum}</span>
          {
            loading
              ? <Spin style={{ height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }} size="middle"></Spin>
              : <div className="quorum-network">
                <CommonTitle title="我的网络"/>
                <div className="network-list">
                  <div className="item-add" onClick={() => this.gotoCreateNetwork()}>
                    <div className="quorum-plus plus">
                      <PlusOutlined />
                    </div>
                    <div className="add-tit">新建网络</div>
                  </div>
                  {
                    networkList && networkList.length ? networkList.map(item => {
                      return (
                        <div key={item.id} className={item.status === 'running' ? `network-item  ${item.status}-item` : `network-item  ${item.status}-item disabled-click`} onClick={() => { this.enterDetail(item) }}>
                          <div className="item-name">
                            { this.renderStatus(item.status) }
                            <span className="name">{item.name}</span>
                            {/* { this.renderName(item.name, 28) } */}
                            { this.renderOperation(item) }
                            {/* <div className="domain">help.aliyun.com</div> */}
                          </div>
                          <div className="diver"></div>
                          <div className="item-info"><span className="label">共识算法</span><span>{ item.consensus }</span></div>
                          <div className="item-info"><span className="label">节点数</span><span>{ item.nodeNum }</span></div>
                          <div className="item-info" title={item.creatorName}><span className="label">创建者</span><span>{ item.creatorName.slice(0, 10) + '...' }</span></div>
                          <div className="item-info">
                            <span className="label">有效时间</span>
                            <span>
                              { item.createTime ? moment(item.createTime).format('YYYY.MM.DD') : '-' } 至 &nbsp;

                              { item.status === 'failed' ? '-' : (timeVisible ? (item.dueTime ? moment(item.dueTime).format('YYYY.MM.DD') : '-') : '-')}
                            </span>
                          </div>
                        </div>
                      )
                    }) : null
                  }
                </div>
              </div>
          }
        </div>
      )
    }
}

export default QuorumCom
